import array
import ola_client_wrapper

class olaIO(object):
    def __init__(self):
        self.universes = {}
        self.pendingCalls = 0
        self.wrapper = ola_client_wrapper.ClientWrapper()
        self.client = self.wrapper.Client()
        self.reqUniverseInfo()
    def sentCall(self):
        self.pendingCalls += 1
        self.wrapper.Run()
    def recvdCall(self):
        self.pendingCalls -= 1
        if self.pendingCalls == 0:
            self.wrapper.Stop()
    def reqUniverseInfo(self):
        self.client.FetchUniverses(self.recvUniverseInfo)
        self.sentCall()
    def recvUniverseInfo(self, state, univData):
        for univ in univData:
            self.universes.update({univ.id:olaUniverse(univ.id, univ.name, univ.merge_mode)})
            print self.universes[univ.id]
        self.recvdCall()
    def sendDMX(self, olaUnivID=None):
        if olaUnivID is None:
            for key, val in self.universes.iteritems():
                self.client.SendDmx(key, val.values, self.DMXSent)
                self.sentCall()
        else:
            self.client.SendDmx(olaUnivID, self.universes[olaUnivID].values, self.DMXSent)
            self.sentCall()
    def DMXSent(self, state):
        self.recvdCall()
    def updateDMXValue(self, deviceSysUnivID, chan, value):
        olaUnivToSend = set()
        for key, val in self.universes.iteritems():
            if val.deviceSysUnivID == deviceSysUnivID:
                val.values[chan] = value
                olaUnivToSend.add(key)
                print 'univ=' + str(key) + ', chan=' + str(chan) + ', value=' + str(value)
        for univID in olaUnivToSend:
            self.sendDMX(univID)
class olaUniverse(object):
    def __init__(self, id, name, mergeMode, deviceSysUnivID=None):
        self.id = id
        self.name = name
        self.mergeMode = mergeMode
        self.deviceSysUnivID = deviceSysUnivID
        self.values = array.array('B')
        self.values.extend([0] * 512)
    
